package com.factory.test.activity;

import android.app.ProgressDialog;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.factory.test.R;
import com.factory.test.base.BaseTestActivity;
import com.google.android.exoplayer2.ExoPlayer;


import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.interfaces.IVLCVout;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.videolan.libvlc.Media;

/**
 * IP 摄像头测试
 */
public class IPCameraActivity extends BaseTestActivity implements SurfaceHolder.Callback{

    private TextView tvStatus;
    private TextView tvStatus1;
    private SurfaceView surfaceView;
    private ExoPlayer exoPlayer;
    private ExecutorService executor;
    private Handler handler;
    private Surface currentSurface;
    private LibVLC mLibVLC;
    private org.videolan.libvlc.MediaPlayer mMediaPlayer;
    private org.videolan.libvlc.MediaPlayer mMediaPlayer1;
    IVLCVout vout;
    IVLCVout vout1;
    private void initVLC() {
        final ArrayList<String> options = new ArrayList<>();
        options.add("--network-caching=300");
        options.add("--rtsp-tcp");
        options.add("--avcodec-skiploopfilter=4");
        options.add("--avcodec-skip-idct=4");
        options.add("--avcodec-skip-frame=4");

        mLibVLC = new LibVLC(this, options);
        mMediaPlayer = new org.videolan.libvlc.MediaPlayer(mLibVLC);
        mMediaPlayer1 = new org.videolan.libvlc.MediaPlayer(mLibVLC);
//        mMediaPlayer.setEventListener(event -> handlePlayerEvent(event));
        // 设置视频输出
        vout = mMediaPlayer.getVLCVout();
        vout1 = mMediaPlayer1.getVLCVout();
        vout.setVideoView(mVideoSurface);
        vout1.setVideoView(mVideoSurface1);
        vout.attachViews();
        vout1.attachViews();
    }
    public class ViewClick{}
    private String mCurrentRtspUrl;
    private void connectToCamera(String ip) {
        // 构建RTSP URL
        String rtspUrl = ip;
//        mCurrentRtspUrl = rtspUrl;


        // 创建媒体
        Media media = new Media(mLibVLC, Uri.parse(rtspUrl));
        media.setHWDecoderEnabled(true, false);
        media.addOption(":network-caching=300");
        media.addOption(":rtsp-tcp");

        // 设置媒体并播放
        mMediaPlayer.setMedia(media);
        mMediaPlayer.play();

        // 保存连接信息
//        saveCameraConnection(ip, port, username, password);
//        showSnackbar("正在连接: " + ip);
    }

    private void connectToCamera1(String ip) {
        // 构建RTSP URL
        String rtspUrl = ip;
//        mCurrentRtspUrl = rtspUrl;


        // 创建媒体
        Media media = new Media(mLibVLC, Uri.parse(rtspUrl));
        media.setHWDecoderEnabled(true, false);
        media.addOption(":network-caching=300");
        media.addOption(":rtsp-tcp");

        // 设置媒体并播放
        mMediaPlayer1.setMedia(media);
        mMediaPlayer1.play();

        // 保存连接信息
//        saveCameraConnection(ip, port, username, password);
//        showSnackbar("正在连接: " + ip);
    }
    private SurfaceView mVideoSurface;
    private SurfaceView mVideoSurface1;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.activity_ip_camera);
        mVideoSurface = findViewById(R.id.surfaceView);
        mVideoSurface1 = findViewById(R.id.surfaceView1);
        initVLC();
//        btnScan = findViewById(R.id.btnScan);
        tvStatus = findViewById(R.id.tvStatus);
        tvStatus1 = findViewById(R.id.tvStatus1);
//        surfaceView = findViewById(R.id.surfaceView);
//        surfaceView.getHolder().addCallback(this);

        // 初始化线程池和Handler
        executor = Executors.newFixedThreadPool(20);
        handler = new Handler(Looper.getMainLooper());
        tvStatus.setText("正在扫描摄像头...");
        scanNetwork();
    }


    private void scanNetwork() {
        executor.execute(() -> {
            for (int i = 1; i <= 255; i++) {
                final String ip = "192.168.1." + i;
                executor.execute(() -> {
                    if (isRealCamera(ip)) {
                        Log.d("TAG", "scanNetwork: "+ip);
                        handler.post(() -> startPlayback(ip));
                    }
                });
            }
        });
    }
//    private void playRtspStream(String url) {
//        try {
//            // 创建 RTSP 媒体源
//            RtspMediaSource.Factory rtspFactory = new RtspMediaSource.Factory();
//            MediaItem mediaItem = MediaItem.fromUri(Uri.parse(url));
//            MediaSource mediaSource = rtspFactory.createMediaSource(mediaItem);
//
//            // 设置播放器
//            exoPlayer.setMediaSource(mediaSource);
//            exoPlayer.prepare();
//            exoPlayer.setPlayWhenReady(true);
//
//            // 绑定视频表面
//            if (currentSurface != null) {
//                exoPlayer.setVideoSurface(currentSurface);
//            }
//        } catch (Exception e) {
//            Log.e("RTSP", "播放失败: " + e.getMessage());
//            handler.post(() -> tvStatus.setText("播放失败: " + e.getMessage()));
//        }
//    }

    // 检测IP是否开放RTSP端口
    private boolean isCameraDevice(String ip) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(ip, 554), 500);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    // 增强方案：增加协议级验证（简化示例）
    private boolean isRealCamera(String ip) {
        try (Socket s = new Socket()) {
            s.connect(new InetSocketAddress(ip, 554), 1000);

            // 发送RTSP OPTIONS请求验证
            OutputStream out = s.getOutputStream();
            out.write("OPTIONS * RTSP/1.0\r\n\r\n".getBytes());

            // 验证响应头是否包含RTSP
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String s1="";
            s1 = in.readLine();
            Log.d("TAG", "isRealCamera: "+s1);
            return s1.contains("RTSP/1.0");
        } catch (Exception e) {
            return false;
        }
    }

    // 尝试播放RTSP流
    boolean isfirst=true;
    private void startPlayback(String ip) {
        List<String> rtspTemplates = new ArrayList<>();
        rtspTemplates.add("rtsp://" + ip + ":554/live/0/main");        // 海康威视
        rtspTemplates.add("rtsp://" + ip + ":554/stream1");             // 大华
        rtspTemplates.add("rtsp://admin:admin@" + ip + ":554/live");   // 带默认凭证
        rtspTemplates.add("rtsp://" + ip + ":554/user=admin&password=&channel=1&stream=0.sdp"); // TP-Link

        for (String url : rtspTemplates) {
            try {
                if (isfirst){
                    isfirst=false;
                    tvStatus.setText("已连接: " + ip + "\nURL: " + url);
                    connectToCamera(url);
                }else{
                    tvStatus1.setText("已连接: " + ip + "\nURL: " + url);
                    connectToCamera1(url);
                }


                return;
            } catch (Exception e) {
                Log.e("RTSP", "Failed " + url + ": " + e.getMessage());
            }
        }
        tvStatus.setText("找到设备但无法播放: " + ip);
    }
//    @UnstableApi private void playRtspStreamWithAuth(String url, String username, String password) {
//        // 1. 创建 RTSP 媒体源工厂
//        RtspMediaSource.Factory rtspFactory = new RtspMediaSource.Factory();
//
//        // 2. 设置认证凭证（新API）
//        if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
//            rtspFactory.setCredentials(username, password); // ✅ 核心替代方案
//        }
//
//        // 3. 创建媒体项
//        MediaItem mediaItem = MediaItem.fromUri(Uri.parse(url));
//
//        // 4. 构建媒体源
//        MediaSource mediaSource = rtspFactory.createMediaSource(mediaItem);
//
//        // 5. 配置播放器
//        exoPlayer.setMediaSource(mediaSource);
//        exoPlayer.prepare();
//        exoPlayer.setPlayWhenReady(true);
//    }
//    private void playRtspStream(String url) {
//        DefaultDataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(this);
//        MediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
//                .createMediaSource(MediaItem.fromUri(url));
//
//        exoPlayer.setMediaSource(mediaSource);
//        exoPlayer.prepare();
//        exoPlayer.setPlayWhenReady(true);
//
//        if (currentSurface != null) {
//            exoPlayer.setVideoSurface(currentSurface);
//        }
//    }

    // SurfaceHolder 回调方法
    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        currentSurface = holder.getSurface();
        exoPlayer.setVideoSurface(currentSurface);
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
        currentSurface = holder.getSurface();
        exoPlayer.setVideoSurface(currentSurface);
    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
        exoPlayer.setVideoSurface(null);
        currentSurface = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        exoPlayer.release();
        if (mMediaPlayer!=null){
//            mMediaPlayer.stop();
            mMediaPlayer.release();
        }
        if (mMediaPlayer1!=null){
//            mMediaPlayer1.stop();
            mMediaPlayer1.release();
        }


        mLibVLC.release();
        executor.shutdownNow();
    }






    private String formatTime(long time){
        long s = 1000;
        long m = s * 60;
        long minute = time / m;        //单位分
        long second = (time - (minute * m)) / s;    //单位秒
        return String.format(Locale.CHINA, "%02d:%02d", minute, second);
    }


}
